package com.jp.knowledge.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jiayen.view.TabItemView;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.JpApplicationWebActivity;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.activity.WebMainActivity;
import com.jp.knowledge.adapter.CusAdaper;
import com.jp.knowledge.adapter.TiYanAdapter;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.Banner;
import com.jp.knowledge.model.ExpData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.CustomScrollViewPager;
import com.jp.knowledge.view.DotLayout;
import com.jp.knowledge.view.WrapGridVIew;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 体验fragment
 */
public class TiYanFragment_old extends BaseFragment implements ResultSubscriber.OnResultListener, View.OnClickListener {

    private final int GET_BANNAR_CODE = 0x00000000001;//获取bannar数据
    private final int GET_HOME_CODE = 0x00000000002;//获取首页数据

    private View mView;//主页view
    private CustomScrollViewPager imgPager;

    private TextView topName;
    private TextView topDesc;
    private TabItemView offical;//官方

    private TabItemView special;//专题

    private TabItemView industry;//行业
    private TabItemView myTiyan;//我的体验;
    private TabItemView[] itemViews;

    private RelativeLayout newLayout;//查看全部最新体验

    private RelativeLayout hotLayout;//查看全部最热体验

    private WrapGridVIew newTiyan;//最新体验列表

    private WrapGridVIew hotTiyan;//最热体验列表

    private CanRefreshLayout mRefresh;//刷新layout

    private ListView listView;//listView数据加载

    private View headView;//头部view

    private DotLayout dotLayout;

    private RelativeLayout specialLayout;

    private CusAdaper newAdapter;
    private CusAdaper hotAdapter;

    private  ExpData expData;//首页数据

    String[] headNames = new String[]{"官方", "专题", "行业", "我的体验"};
    int[] headImgs = new int[]{R.mipmap.kuaitiyanguanfang, R.mipmap.kuaitiyanzhuanti, R.mipmap.kuaitiyanhangye, R.mipmap.kuaitiyanzhizuo};

    private TiYanAdapter adapter;

    private FileCacheManager cacheManager;
    private String CACHE_BANNER_PATH;//banner缓存路径
    private String CACHE_HOME_PATH;//首页数据缓存路径

    /**
     * 设置轻体验
     */
    private void setTiyan() {
        topName.setText("体验");
        topDesc.setText("免安装产品体验");
        rightIcon.setOnClickListener(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_ti_yan, null);
        headView = inflater.inflate(R.layout.fragment_ti_yan_head, null);
        initData();
        return mView;
    }

    private void initData() {

        initHead(mView);
        initView();

        // 初始化头部信息块
        initHeadView();

        cacheManager = new FileCacheManager();
        CACHE_BANNER_PATH = getContext().getCacheDir() + "/banner_" + HttpHelper.uuid + ".dat";//banner缓存路径
        CACHE_HOME_PATH = getContext().getCacheDir() + "/home_" + HttpHelper.uuid + ".dat";//首页数据缓存路径
        mRefresh = (CanRefreshLayout) mView.findViewById(R.id.refresh);
        listView = (ListView) mView.findViewById(R.id.can_content_view);
        mRefresh.setLoadMoreEnabled(false);
        mRefresh.setRefreshEnabled(false);
        listView.addHeaderView(headView);
        setTiyan();
        //读取缓存数据
        readCacheData();
//        //获取数据
//        getBannar();
//        getHomeData();

        //去到web页面加载数据
        setToWebListerner();
    }

    /**
     * 读取缓存数据
     */
    private void readCacheData() {

        loadingDialog.show();
        //读取banner缓存
        Observable.create(new Observable.OnSubscribe<Map<String, Object>>() {
            @Override
            public void call(Subscriber<? super Map<String, Object>> subscriber) {
                List<Banner> banner = (List<Banner>) cacheManager.readObject(CACHE_BANNER_PATH);
                ExpData expData = (ExpData) cacheManager.readObject(CACHE_HOME_PATH);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("banner", banner);
                map.put("expData", expData);
                subscriber.onNext(map);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Map<String, Object>>() {
                    @Override
                    public void onCompleted() {
                        loadingDialog.cancel();
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.cancel();
                        getBannar();
                        getHomeData();
                    }

                    @Override
                    public void onNext(Map<String, Object> map) {

                        List<Banner> banner = (List<Banner>) map.get("banner");
                        ExpData expData = (ExpData) map.get("expData");
                        if (banner == null || banner.size() == 0) {
                            getBannar();
                        } else {
                            handBannerList(banner);

                                    getBannar();
                        }

                        if (expData == null) {
                            getHomeData();
                        } else {
                            handHomeData(expData);
                                    getHomeData();

                        }

                    }
                });
    }

    /**
     * 初始化view
     */
    private void initView() {

        dotLayout = (DotLayout) headView.findViewById(R.id.dot_layout);

        topName = (TextView) mView.findViewById(R.id.module_name);
        topDesc = (TextView) mView.findViewById(R.id.module_desc);

        imgPager = (CustomScrollViewPager) headView.findViewById(R.id.img_pager);


        offical = (TabItemView) headView.findViewById(R.id.official);

        special = (TabItemView) headView.findViewById(R.id.special);

        industry = (TabItemView) headView.findViewById(R.id.industry);
        myTiyan = (TabItemView) headView.findViewById(R.id.my_tiyan);

        newLayout = (RelativeLayout) headView.findViewById(R.id.new_tiyan_to);

        hotLayout = (RelativeLayout) headView.findViewById(R.id.hot_tiyan_to);
        specialLayout = (RelativeLayout) headView.findViewById(R.id.special_tiyan_to);

        newTiyan = (WrapGridVIew) headView.findViewById(R.id.new_tiyan);

        hotTiyan = (WrapGridVIew) headView.findViewById(R.id.hot_tiyan);



    }


    private WebMainActivity webMainActivity;

    private void setToWebListerner() {
            newLayout.setOnClickListener(webClickListener);
            hotLayout.setOnClickListener(webClickListener);
            special.setOnClickListener(webClickListener);
            industry.setOnClickListener(webClickListener);
            myTiyan.setOnClickListener(webClickListener);
            specialLayout.setOnClickListener(webClickListener);

            newTiyan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String url = "discover/experienceDetail?id=" + expData.getNewData().get(position).getId();
                    JpApplicationWebActivity.gotoWebActivity(mContext, url);
                }
            });

            hotTiyan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String url = "discover/experienceDetail?id=" + expData.getHotData().get(position).getId();
                    JpApplicationWebActivity.gotoWebActivity(mContext, url);
                }
            });


            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (position > 0) {
                        String url = "discover/experience/specialExperienceDetail?id=" + expData.getSpecialData().get(position - 1).getId();
                        JpApplicationWebActivity.gotoWebActivity(mContext, url);
                    }
                }
            });
    }



    /**
     * web点击事件
     */
    private View.OnClickListener webClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "";
            switch (v.getId()) {
                case R.id.new_tiyan_to://最新体验
                    url = "discover/newExperience";
                    break;
                case R.id.special_tiyan_to://热门专题
                    url = "discover/specialExperience";
                    break;
                case R.id.hot_tiyan_to://最热体验
                    url = "discover/hotExperience";
                    break;
                case R.id.special://专题
                    url = "discover/specialExperience";
                    break;
                case R.id.industry://行业
                    url = "discover/industryExperience";
                    break;
                case R.id.my_tiyan://我的体验
                    url = "discover/myExperience";
                    break;
                default:
                    break;

            }
            JpApplicationWebActivity.gotoWebActivity(mContext, url);
        }
    };

    /**
     * 获取banna数据
     */
    public void getBannar() {
        JsonObject param = new JsonObject();
        HttpHelper.getInstance(mContext).discoverExpBanner(param, GET_BANNAR_CODE, this);
    }

    /**
     * 获取首页数据
     */
    public void getHomeData() {
        JsonObject param = new JsonObject();
        HttpHelper.getInstance(mContext).discoverExpData(param, GET_HOME_CODE, this);

    }

    /**
     * 初始化头部信息块
     */
    private void initHeadView() {
        int size = headNames.length;
        itemViews = new TabItemView[size];
        itemViews[0] = offical;
        itemViews[1] = special;
        itemViews[2] = industry;
        itemViews[3] = myTiyan;
        for (int i = 0; i < size; i++) {
            itemViews[i].setIcon(headImgs[i]);
            itemViews[i].setname(headNames[i]);
            itemViews[i].setNameColor(R.color.font_black_think);
        }
    }

    @Override
    public void onStart(int requestType) {
        loadingDialog.show();
    }

    @Override
    public void onCompleted(int requestType) {
        loadingDialog.cancel();
    }

    @Override
    public void onError(int requestType) {
        loadingDialog.cancel();
    }

    @Override
    public void onNext(IModel data, int requestType) {
        int code = data.getErrcode();
        if (code == 0) {
            if (requestType == GET_BANNAR_CODE) {
                List<Banner> list = data.getList(Banner.class);
                saveCache(list);
                handBannerList(list);//处理banner图片列表
            } else if (requestType == GET_HOME_CODE) {
                ExpData list = data.getEntity(ExpData.class);
                saveCache(list);
                handHomeData(list);//处理首页数据
            }
        } else {
            ToasUtil.toast(mContext, data.getMessage());
        }
    }


    /**
     * 保存缓存
     *
     * @param obj
     */
    private void saveCache(final Object obj) {
        //保存缓存
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(obj, CACHE_HOME_PATH);
            }
        }).start();
    }

    /**
     * 处理首页数据
     *
     * @param data
     */
    private void handHomeData(final ExpData data) {
        expData = data;

        if (newAdapter == null) {
            newAdapter = new CusAdaper(data.getNewData(), mContext);
            newTiyan.setAdapter(newAdapter);//设置最新体验数据
        } else {
            newAdapter.update(data.getNewData());
        }

        if (hotAdapter == null) {
            hotAdapter = new CusAdaper(data.getHotData(), mContext);
            hotTiyan.setAdapter(hotAdapter);//设置最热体验数据
        } else {
            hotAdapter.update(data.getHotData());
        }


        //设置专题数据
        if (adapter == null) {
            adapter = new TiYanAdapter(mContext, data.getSpecialData());
            listView.setAdapter(adapter);
        } else {
            adapter.updataAdapter(data.getSpecialData());
        }

    }

    /**
     * 处理banner列表
     *
     * @param list
     */
    private void handBannerList(final List<Banner> list) {
        if (list != null)
            dotLayout.initView(list.size());
        imgPager.update(list, dotLayout);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_serach:
                startActivity(new Intent(mContext, SearchActivity.class));
            break;
            default:
                break;
        }
    }
}

